const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

// 开发一个用于去除打包生成 js 文件块级注释的插件
class MyPlugin {
  // 接收 webpack 的核心对象
  apply (compiler) {
    // emit 钩子，在将文件输出到目标目录前执行
    // 在 emit 钩子上挂载方法
    compiler.hooks.emit.tap('MyPlugin', (compilation) => {
      // compilation 可以理解为此次打包的上下文
      // console.log(name)
      // console.log(compilation.assets[name])
      for (const name in compilation.assets) {
        if (name.endsWith('.js')) {
          const contents = compilation.assets[name].source()
          // 去除 js 文件内的注释
          const withoutComments = contents.replace(/\/\*\*+\*\//g, '')
          compilation.assets[name] = {
            source: () => withoutComments,
            size: () => withoutComments.length
          }
        }
      }
    })
  }
}

module.exports = {
  mode: 'none',
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.png$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 2 * 1024
          }
        }
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    // 默认生成 index.html
    new HtmlWebpackPlugin({
      title: 'Webpack Plugin Sample',
      meta: {
        viewport: 'width=device-width'
      },
      template: './index.html'
    }),
    // 生成 about.html
    new HtmlWebpackPlugin({
      filename: 'about.html'
    }),
    new CopyWebpackPlugin({
      patterns: [
        {from: 'public', to: '.'}
      ]
    }),
    new MyPlugin()
  ]
}
